﻿import os
import sys
from PyQt5 import QtCore, QtGui,QtWidgets, QtWidgets ,uic
from PyQt5.QtCore import Qt, QThread,pyqtSignal
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QImage
from PIL import Image
from PIL.ImageQt import ImageQt
import time
import datetime
import socket
import requests
from uiDef import *

palette = QPalette()

def UpdateWeatherIcon(tempType):  #匹配天气类型图标
    if(tempType == "晴"):
        return "Qing"
    elif(tempType == "多云"):
        return "DuoYun"
    elif(tempType == "小雨"):
        return "XiaoYu"
    elif(tempType == "大雨"  or tempType == "中到大雨"):
        return "DaYu"
    elif(tempType == "暴雨"  or tempType == "大暴雨" or 
        tempType == "特大暴雨" or tempType == "大到暴雨" or
        tempType == "暴雨到大暴雨" or tempType == "大暴雨到特大暴雨"):
        return "BaoYu"
    elif(tempType == "沙尘暴" or tempType == "浮尘" or
        tempType == "扬沙" or tempType == "强沙尘暴" or
        tempType == "霾"):
        return "Mai"
    else:
        return "undefined"
    return(tempType)

def LowTempStr(tempStr):
    temp_L = tempStr.replace("低温","")
    temp_L = temp_L.replace("℃","")
    temp_L = temp_L.replace(" ","")
    return temp_L

def HightTempStr(tempStr):
    temp_H = tempStr.replace("高温","")
    temp_H = temp_H.replace("℃","")
    temp_H = temp_H.replace(" ","")
    return temp_H


def printWeatherInfo(info):
    print(info['city'])
    
    print(info['Today']['date'])
    print(info['Today']['low'])
    print(info['Today']['high'])
    print(info['Today']['type'])
    print(info['Today']['fx'])
    print(info['Today']['fl'])
    
    print(info['Day1']['date'])
    print(info['Day1']['low'])
    print(info['Day1']['high'])
    print(info['Day1']['type'])
    print(info['Day1']['fx'])
    print(info['Day1']['fl'])
    
    print(info['Day2']['date'])
    print(info['Day2']['low'])
    print(info['Day2']['high'])
    print(info['Day2']['type'])
    print(info['Day2']['fx'])
    print(info['Day2']['fl'])
    
    print(info['Day3']['date'])
    print(info['Day3']['low'])
    print(info['Day3']['high'])
    print(info['Day3']['type'])
    print(info['Day3']['fx'])
    print(info['Day3']['fl'])

def printDict(info):
    for key in info.keys():
        print(key + ": " + str(info[key]))


#获取天气
def getWeatherInfo(cityCode = '101210101'):
    weatherInfo = {'city':None, 'Today':None, 'Day1':None, 'Day2':None, 'Day3':None}
    todayInfo = {'date':None, 'low':None, 'high':None, 'type':None, 'fx':None}
    day1Info = {'date':None, 'low':None, 'high':None, 'type':None, 'fx':None}
    day2Info = {'date':None, 'low':None, 'high':None, 'type':None, 'fx':None}
    day3Info = {'date':None, 'low':None, 'high':None, 'type':None, 'fx':None}
    weatherInfo['Today'] = todayInfo
    weatherInfo['Day1'] = day1Info
    weatherInfo['Day2'] = day2Info
    weatherInfo['Day3'] = day3Info

    #return weatherInfo 
    
    try:    
        # 连接超时,6秒，下载文件超时,7秒
        r = requests.get('http://t.weather.itboy.net/api/weather/city/'+cityCode,timeout=(6,7))

        #今日
        todayInfo['date'] = str(r.json()['data']['forecast'][0]['ymd'])  #日期
        todayInfo['low'] = str(r.json()['data']['forecast'][0]['low'])   #最低温度
        todayInfo['high'] = str(r.json()['data']['forecast'][0]['high']) #最高温度
        todayInfo['type'] = str(r.json()['data']['forecast'][0]['type']) #天气类型
        todayInfo['fx'] = str(r.json()['data']['forecast'][0]['fx'])     #风向
        todayInfo['fl'] = str(r.json()['data']['forecast'][0]['fl'])     #风力

        #明天
        day1Info['date'] = str(r.json()['data']['forecast'][1]['ymd'])
        day1Info['low'] = str(r.json()['data']['forecast'][1]['low'])
        day1Info['high'] = str(r.json()['data']['forecast'][1]['high'])
        day1Info['type'] = str(r.json()['data']['forecast'][1]['type'])
        day1Info['fx'] = str(r.json()['data']['forecast'][1]['fx'])
        day1Info['fl'] = str(r.json()['data']['forecast'][1]['fl'])

        #后天
        day2Info['date'] = str(r.json()['data']['forecast'][2]['ymd'])
        day2Info['low'] = str(r.json()['data']['forecast'][2]['low'])
        day2Info['high'] = str(r.json()['data']['forecast'][2]['high'])
        day2Info['type'] = str(r.json()['data']['forecast'][2]['type'])
        day2Info['fx'] = str(r.json()['data']['forecast'][2]['fx'])
        day2Info['fl'] = str(r.json()['data']['forecast'][2]['fl'])

        #大后天
        day3Info['date'] = str(r.json()['data']['forecast'][3]['ymd'])
        day3Info['low'] = str(r.json()['data']['forecast'][3]['low'])
        day3Info['high'] = str(r.json()['data']['forecast'][3]['high'])
        day3Info['type'] = str(r.json()['data']['forecast'][3]['type'])
        day3Info['fx'] = str(r.json()['data']['forecast'][3]['fx'])
        day3Info['fl'] = str(r.json()['data']['forecast'][3]['fl'])

        #汇总
        weatherInfo['city'] = str(r.json()['cityInfo']['city']) #城市
        weatherInfo['Today'] = todayInfo
        weatherInfo['Day1'] = day1Info
        weatherInfo['Day2'] = day2Info
        weatherInfo['Day3'] = day3Info
        
        printDict(weatherInfo)
        return weatherInfo
    except:
        print("err")
        return weatherInfo


def todayWeek(nowWeek):
    if nowWeek == "0":
        return"星期天"
    elif nowWeek =="1":
        return"星期一"
    elif nowWeek =="2":
        return"星期二"
    elif nowWeek =="3":
        return"星期三"
    elif nowWeek =="4":
        return"星期四"
    elif nowWeek =="5":
        return"星期五"
    elif nowWeek =="6":
        return"星期六"

def ImageLoad(imageName,scale):
    img = QPixmap("resource/weatherType/"+imageName+".png")
    width = img.width()
    img = img.scaledToWidth(int(width * scale))
    return img
 
class WeatherShow(QtWidgets.QMainWindow):
    def __init__(self):
        super(WeatherShow, self).__init__()
        uic.loadUi("weather.ui", self)
        QtGui.QFontDatabase.addApplicationFont("myFont.ttf")
        
        weatherInfo = getWeatherInfo()
        self.setWeather(weatherInfo)
        
        #信号与槽
        self.comboBox.currentIndexChanged.connect(self.changeCity)
        self.homeBtn.clicked.connect(self.returnHome)
        self.homeBtn.clicked.connect(self.close)
        
        self.initUI()

    # 初始化界面
    def initUI(self):
        self.resize(WIN_WIDTH, WIN_HEIGHT)
        self.setWindowTitle('天气信息')
        
        palette = QPalette() #启动时先设一个背景
        palette.setBrush(QPalette.Background, QBrush(QPixmap("resource/bg/bg_weather.png").scaled(self.width(),self.height())))
        self.setPalette(palette)
        
        self.show()

    def changeCity(self,index):
        print("chageIdx:{}", index)
        cityCode = "101210101"
        if index == 0: #杭州
            cityCode = "101210101"
        elif index == 1: #北京
            cityCode = "101010100"
        elif index == 2: #广州
            cityCode = "101280101"
        elif index == 3: #武汉
            cityCode = "101200101"
        elif index == 4: #郑州
            cityCode = "101180101"

        weatherInfo = getWeatherInfo(cityCode)
        self.setWeather(weatherInfo)
            
    # 返回主页
    def returnHome(self):
        print("return home")
        from homeUI import mainWindow
        self.homeWindow = mainWindow()
        self.homeWindow.show()
       
    def TimeTick(self,msg,msg2,msg3): 
        self.time_Label.setText(msg) 
        self.week_Label.setText(msg2)
        self.month_Label.setText(msg3)

    def setWeather(self, weatherInfo):
        if (weatherInfo['city'] == None):
            return
    
        self.city_name.setText(weatherInfo['city'])
        self.city_name.setStyleSheet('QLabel {color: white}')
        #今天
        tmpData = weatherInfo['Today']
        #print(tmpData)
        self.day0_date.setText(tmpData['date'])
        self.day0_date.setStyleSheet('QLabel {color: white}')
        self.Icon_Today.setPixmap(ImageLoad(UpdateWeatherIcon(tmpData['type']),0.8))
        self.today_Weather.setText(tmpData['type'])
        self.today_Temp.setText(LowTempStr(tmpData['low']) + "~" + HightTempStr(tmpData['high']) +"度")
        self.today_wind.setText(tmpData['fx']+": "+tmpData['fl'])
        
        #明天
        tmpData = weatherInfo['Day1']
        #print(tmpData)
        self.day1_date.setText(tmpData['date'])
        self.day1_date.setStyleSheet('QLabel {color: white}')
        self.icon_Tomorrow.setPixmap(ImageLoad(UpdateWeatherIcon(tmpData['type']),0.6))
        tomorrowStr = tmpData['type'] +" "+ LowTempStr(tmpData['low']) + "~" + HightTempStr(tmpData['high']) +"度"
        self.tomorrow_Temp.setText(tomorrowStr)
        self.tomorrow_wind.setText(tmpData['fx']+": "+tmpData['fl'])

        #后天
        tmpData = weatherInfo['Day2']
        #print(tmpData)
        self.day2_date.setText(tmpData['date'])
        self.day2_date.setStyleSheet('QLabel {color: white}')
        self.icon_Acquired.setPixmap(ImageLoad(UpdateWeatherIcon(tmpData['type']),0.6))
        AcquiredStr = tmpData['type'] +" "+ LowTempStr(tmpData['low']) + "~" + HightTempStr(tmpData['high']) +"度"
        self.acquired_Temp.setText(AcquiredStr)
        self.acquired_wind.setText(tmpData['fx']+": "+tmpData['fl'])

        #大后天
        tmpData = weatherInfo['Day3']
        #print(tmpData)
        self.day3_date.setText(tmpData['date'])
        self.day3_date.setStyleSheet('QLabel {color: white}')
        self.icon_afterTomorrow.setPixmap(ImageLoad(UpdateWeatherIcon(tmpData['type']),0.6))
        afterTomorrowStr = tmpData['type'] +" "+ LowTempStr(tmpData['low']) + "~" + HightTempStr(tmpData['high']) +"度"
        self.afterTomorrow_Temp.setText(afterTomorrowStr)
        self.afterTomorrow_wind.setText(tmpData['fx']+": "+tmpData['fl'])


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = WeatherShow()
    sys.exit(app.exec_())
